package com.ang.juc.n2;

public class DeadLockTest2_1 {
    String o1 = "筷子1";
    String o2 = "筷子2";
    String o3 = "筷子3";
    String o4 = "筷子4";
    String o5 = "筷子5";

    class Person {
        String name;

        public Person(String name) {
            this.name = name;
        }
    }

    Person person1 = new Person("小1");
    Person person2 = new Person("小2");
    Person person3 = new Person("小3");
    Person person4 = new Person("小4");
    Person person5 = new Person("小5");

    //动作，锁住筷子1和2，并且吃饭
    public Runnable eatRunnable(Person person, Object o1, Object o2) {
        return () -> {
            String name = person.name;
            while (true) {
                System.out.println(name + "准备拿：" + o1 + "和" + o2);
                synchronized (o1) {
                    StringBuffer sb = new StringBuffer("    " + name + "拿到了：" + o1);
                    synchronized (o2) {
                        sb.append("    " + name + "拿到了：" + o2);
                        sb.append("    " + name + "使用：[" + o1 + "] 和 [" + o2 + "] 吃饭");

                        System.out.println(sb);
                    }
                }
            }
        };
    }

    //执行，创建5个线程，每个线程分配：1个人和2支筷子，并启动
    public void test1() {
        Thread t1 = new Thread(eatRunnable(person1, o1, o2));
        Thread t2 = new Thread(eatRunnable(person2, o2, o3));
        Thread t3 = new Thread(eatRunnable(person3, o3, o4));
        Thread t4 = new Thread(eatRunnable(person4, o4, o5));
        Thread t5 = new Thread(eatRunnable(person5, o5, o1));

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }

    //=====================================
    public static void main(String[] args) {
        System.out.println("rice-----------------------");
        DeadLockTest2_1 rice = new DeadLockTest2_1();
        rice.test1();
    }
}
